<template>
  <div class="message-container" v-loading="loading">
    <LeftMenu
      :activeMenu="activeMenu"
      :leftNum="leftCount"
      @menuChange="leftMenuChange"
    ></LeftMenu>
    <div class="msg_r">
      <div class="top">
        <ol>
          <li
            v-for="(item, index) in topList"
            :key="index"
            :class="index == activeTopIndex ? 'li_active' : ''"
            @click="topMenuChange(index)"
          >
            {{ item }}
          </li>
        </ol>
      </div>
      <Search
        v-model="formData"
        :activeMenu="activeMenu"
        @toSearch="toSearch"
        @allRead="allRead"
      ></Search>
      <div class="btm">
        <ComTable
          :table-data="tableData"
          :columns="commonColumns"
          :showSelection="false"
          :tableHeight="tableHeight"
          :loading="false"
          v-if="!loading"
        >
          <el-table-column slot="isRead" width="40px">
            <template slot-scope="scope">
              <span
                :class="scope.row.isRead == 1 ? 'has_read' : 'un_read'"
              ></span>
            </template>
          </el-table-column>
          <el-table-column slot="realname" label="操作人">
            <template slot-scope="scope">
              <span v-if="scope.row.type" :class="opacityClass(scope.row)">{{
                realsname(scope.row)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column slot="title" label="学员姓名">
            <template slot-scope="scope">
              <span
                class="link_to"
                :class="opacityClass(scope.row)"
                @click="rowClick(scope.row, 'vipStudents')"
                >{{ scope.row.title }}</span
              >
            </template>
          </el-table-column>
          <el-table-column slot="status" label="状态">
            <template slot-scope="scope">
              <span :class="opacityClass(scope.row)">
                {{ returnStatus(scope.row) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column slot="comefrom" label="数据来源">
            <template slot-scope="scope">
              <span :class="opacityClass(scope.row)">{{
                dataComefrom(scope.row)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column slot="content" label="消息内容" min-width="150">
            <template slot-scope="scope">
              <p :class="opacityClass(scope.row)">
                {{ contentName(scope.row, 1) }}
                <span class="" v-if="activeMenu == 1">{{
                  contentCenterName(scope.row)
                }}</span>
                <span
                  class="link_to"
                  @click="rowClick(scope.row)"
                  v-else-if="
                    activeMenu != 6 && activeMenu != 7 && activeMenu != 8
                  "
                  >{{ contentCenterName(scope.row) }}</span
                >
                {{ contentName(scope.row, 2) }}
              </p>
            </template>
          </el-table-column>
          <el-table-column slot="names" label="名称" min-width="90">
            <template slot-scope="scope">
              <p :class="opacityClass(scope.row)">
                {{ contentName(scope.row, 1, true) }}
                <span class="link_to" @click="rowClick(scope.row)">{{
                  contentCenterName(scope.row)
                }}</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column slot="failReason" label="失败原因">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="seeFailsReason(scope.row)"
                :class="opacityClass(scope.row)"
                v-if="errNumber(scope.row.content) > 0 && scope.row.valid == 1"
                >查看</el-button
              >
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column slot="operate" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showDetail(scope.row)"
                :class="opacityClass(scope.row)"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </ComTable>
        <div class="p-contianer">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            :pager-count="5"
            class="p-bar"
            background
            layout="prev, pager, next, sizes, total, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 消息详情 -->
    <MessageInfo
      :msgInfo="msgInfo"
      :showVisible="showVisible"
      :activeMenu="activeMenu"
    ></MessageInfo>
    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :visible.sync="$store.state.crm.showDetail"
      :crm-type="rowType"
      :id="rowID"
      :isAgreement="false"
      class="d-view"
      @handle="handleHandle"
    />
  </div>
</template>
<script>
import ComTable from "@/components/ComTable/index"; //表格
import MessageInfo from "./components/MessageInfo.vue"; //消息详情
import Search from "./components/Search.vue"; //搜索栏
import LeftMenu from "./components/LeftMenu.vue"; //左侧菜单
import CRMAllDetail from "@/views/crm/components/CRMAllDetail"; //相关详情页面
import {
  messagePageList,
  readMessage,
  readMessageByLabelType,
  queryMessageNum
} from "@/api/message/message.js";
import { crmDownImportErrorAPI } from "@/api/crm/common";
import { downloadExcelWithResData } from "@/utils";
import { mapState, mapMutations } from "vuex";
export default {
  /**
   * 消息中心
   */
  components: {
    ComTable,
    MessageInfo,
    Search,
    LeftMenu,
    CRMAllDetail
  },
  data() {
    return {
      activeMenu: 0, //左侧tab选中项
      activeTopIndex: 0, //顶部tab选中项
      topList: ["全部", "已读", "未读"],
      formData: {
        title: "",
        dateTime: []
      },
      loading: false,
      tableData: [], //table数据
      tableHeight: document.documentElement.clientHeight - 271, //table高度
      msgInfo: "", //详情内容
      showVisible: false,
      // 分页
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      // 详情相关数据
      // showDview: false,
      rowType: "",
      rowID: "",
      // 表格行透明度
      opacityVal: 0.8,
      leftNum: [] //未读条数
    };
  },
  created() {
    this.inIntList();
    this.getUnreadNum();
  },
  mounted() {
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 271;
    };
  },
  methods: {
    ...mapMutations(["SET_showDetail"]),
    /**
     * 未读消息条数
     */
    async getUnreadNum(type) {
      const { data } = await queryMessageNum();
      let leftNum = [
        data.enrolCount,
        data.dropoutCount,
        data.overdueCount,
        data.contractCount,
        data.receivablesCount,
        data.refundCount,
        data.exportCount,
        data.changeCount,
        data.agreementCount
      ];
      this.$store.commit("SET_MSGiNFO", {
        allCount: data.allCount,
        leftCount: leftNum
      });
    },
    /**
     * 左侧菜单切换
     */
    leftMenuChange(e) {
      this.activeMenu = e;
      this.activeTopIndex = 0;
      this.inIntList();
    },
    /**
     * 搜索
     */
    toSearch() {
      this.currentPage = 1;
      this.pageSize = 15;
      this.total = 0;
      this.getList();
    },
    /**
     * 更改已读未读状态
     */
    readsMessage(row) {
      if (row.isRead == 0) {
        readMessage({
          messageId: row.messageId
        }).then(res => {
          this.getUnreadNum();
          this.$set(row, "isRead", 1);
          this.$set(row, "opacity", this.opacityVal);
          // if(this.activeTopIndex == 2){
          //   this.inIntList()
          // }
        });
      }
    },
    /**
     * 查看详情
     */
    showDetail(row) {
      this.readsMessage(row);
      this.msgInfo = this.contentName(row, 3);
      this.showVisible = Date.now();
    },
    /**
     * 全部标记为已读
     */
    allRead() {
      readMessageByLabelType({
        labelType: this.activeMenu
      }).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg);
          this.getUnreadNum();
          this.inIntList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    /**
     * 获取列表数据
     */
    getList() {
      this.loading = true;
      let passData = {
        labelType: this.activeMenu,
        page: this.currentPage,
        limit: this.pageSize
      };
      if (this.formData.title) {
        passData.title = this.formData.title;
      }
      if (this.formData.dateTime && this.formData.dateTime.length > 0) {
        passData.startTime = this.formData.dateTime[0];
        passData.endTime = this.formData.dateTime[1];
      }
      if (this.activeTopIndex == 1) {
        passData.isRead = 1;
      } else if (this.activeTopIndex == 2) {
        passData.isRead = 0;
      }
      messagePageList(passData).then(res => {
        this.tableData = res.data.list;
        this.tableData.forEach(item => {
          if (item.isRead == 0) {
            this.$set(item, "opacity", 1);
          } else {
            this.$set(item, "opacity", this.opacityVal);
          }
        });
        this.total = res.data.totalRow;
        this.loading = false;
      });
    },
    /**
     * 更改每页展示数量
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    /**
     * 初始化列表
     */
    inIntList() {
      this.currentPage = 1;
      this.pageSize = 15;
      this.total = 0;
      this.formData = {};
      this.getList();
    },
    /**
     * 切换顶部menu
     */
    topMenuChange(index) {
      this.activeTopIndex = index;
      this.inIntList();
    },
    handleHandle() {},
    /**
     * 查看导入失败原因
     */
    seeFailsReason(row) {
      this.readsMessage(row);
      this.loading = true;
      crmDownImportErrorAPI({
        messageId: row.messageId
      })
        .then(res => {
          downloadExcelWithResData(res);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * 查看相关详情页面
     */
    rowClick(row, type1) {
      console.log(type1);
      let type = row.type;
      let typeId = row.typeId;
      this.readsMessage(row);
      this.rowID = typeId;
      if (type1) {
        this.rowType = [282, 283].includes(type)
          ? type == 282
            ? "customer"
            : "vipStudents"
          : type1;
      } else {
        if (this.activeMenu == 1) {
          if (type == 47) {
            this.rowType = "contract";
          } else if (type == 49) {
            this.rowType = "refund";
          }
        } else if (this.activeMenu == 7) {
          let leftName = this.getLeftName(type);
          this.rowType = leftName[2];
        } else {
          this.rowType = {
            0: "vipStudents",
            2: "contract",
            3: "contract",
            4: "receivables",
            5: "refund"
          }[this.activeMenu];
        }
      }
      this.SET_showDetail(true);
      // this.showDview = true;
    },
    getLeftName(type, title, realname, submitUserName) {
      return {
        46: [
          "分配VIP学员",
          "VIP学员",
          "分配成功",
          ` VIP学员${title}分配给你，并入学成功`
        ],
        48: [
          "合同状态变更",
          "合同",
          "状态变更",
          `VIP学员${title}的合同状态变更为已逾期`
        ],
        10: [
          "合同审核",
          "合同",
          "审核拒绝",
          `${realname}审核了合同${title}，合同已拒绝`
        ],
        11: [
          "合同审核",
          "合同",
          "审核通过",
          `${realname}审核了合同${title}，合同已通过`
        ],
        98: [
          "合同审核",
          "合同",
          "审核通过",
          `${realname}审核了合同${title}，合同已通过`
        ],
        26: [
          "合同审核",
          "合同",
          "提交审核",
          `${submitUserName}提交了${title}合同审批`
        ],
        12: [
          "回款审核",
          "回款",
          "审核拒绝",
          `${realname}审核了回款${title}，回款已拒绝`
        ],

        13: [
          "回款审核",
          "回款",
          "审核通过",
          `${realname}审核了回款${title}，回款已通过`
        ],
        99: [
          "回款审核",
          "回款",
          "审核通过",
          `${realname}审核了回款${title}，回款已通过`
        ],

        27: [
          "回款审核",
          "回款",
          "提交审核",
          `${submitUserName}提交了${title}回款审批`
        ],

        92: [
          "退款审核",
          "退款",
          "审核通过",
          `${realname}审核了退款${title}，退款已通过`
        ],

        93: [
          "退款审核",
          "退款",
          "审核拒绝",
          `${realname}审核了退款${title}，退款已拒绝`
        ],

        94: [
          "退款审核",
          "退款",
          "提交审核",
          `${submitUserName}提交了${title}退款审批`
        ],
        95: [
          "退款审核",
          "退款",
          "审核通过",
          `${realname}审核了退款${title}，退款已通过`
        ],

        49: [
          "退款审核通过",
          "退款",
          "审核通过",
          `VIP学员${title}的退款审核通过并退学成功`
        ],

        47: [
          "合同状态变更",
          "合同",
          "状态变更",
          `VIP学员${title}的合同状态变更为已退学`
        ],
        18: ["线索导入", "线索"],
        39: ["线索导出", "线索"],
        115: ["学员导出", "学员"],
        38: ["VIP学员导入", "VIP学员"],
        40: ["VIP学员导出", "VIP学员"],
        43: ["合同导出", "合同"],
        44: ["回款导出", "回款"],
        45: ["退款导出", "退款"],
        100: ["线索转移", "线索", "leads", "销售负责人"],
        102: ["线索转移", "线索", "leads", "线索负责人"],
        103: ["线索转移", "线索", "leads", "营销讲师负责人"],
        104: ["学员转移", "学员", "customer", "销售负责人"],
        105: ["学员转移", "学员", "customer", "营销讲师负责人"],
        106: ["VIP学员转移", "VIP学员", "vipStudents", "助教协作人"],
        108: ["合同转移", "合同", "contract", "销售负责人"],
        109: ["合同转移", "合同", "contract", "营销讲师负责人"],
        110: ["回款转移", "回款", "receivables", "销售负责人"],
        111: ["回款转移", "回款", "receivables", "营销讲师负责人"],
        116: ["退款转移", "退款", "refund", "退款负责人"],
        113: ["退款转移", "退款", "refund", "营销讲师负责人"],
        114: ["账单池分配", "合同", "contract", "销售负责人"],
        283: ["VIP学员"],
        282: ["学员"]
      }[type];
    },
    // 内容=>左侧kType=1,右侧kType=2,详情kType=3
    contentName(
      { type, content, stuName, realname, title, submitUserName },
      kType,
      isNames = false
    ) {
      if (this.activeMenu == 6) {
        if (kType == 1) return this.getImportContent(title, content, type);
        else if (kType == 2) return "";
        else if (kType == 3)
          return this.getImportContent(title, content, type, true);
      } else if (this.activeMenu == 7 && !isNames) {
        if (kType == 1) return this.getTransferData(type, content);
        else if (kType == 2) return "";
      }
      // 协议签署
      if (this.activeMenu == 8) {
        if (kType == 1) {
          return content;
        } else if (kType == 3) {
          return `${title} ${content}, 请记得跟进查看`;
        }
        return;
      }
      let n; //左侧内容
      let j; //右侧内容
      let mls; //详情内容
      if (this.activeMenu == 7 && kType == 3) {
        //转移分配详情
        let leftName = this.getLeftName(type, title, realname, submitUserName);
        n = leftName[1];
        mls = `${n}${title}分配给你，请记得跟进查看。`;
        return mls;
      } else {
        let n1 = this.getLeftName(type, title, realname, submitUserName);
        n = n1[1];
        j = n1[2];
        mls = n1[3];
      }
      mls += "，请记得跟进查看。";
      return kType == 1 ? n : kType == 2 ? j : mls;
    },
    // 导出错误条数
    errNumber(content) {
      const list = content ? content.split(",") : [];
      const errSize = Number(list[0] || "0");
      return errSize;
    },
    // 导入导出内容
    getImportContent(title, content, type, isDetail) {
      const list = content ? content.split(",") : [];
      const totalSize = Number(title || "0");
      const updateSize = Number(list[1] || "0");
      const errSize = Number(list[0] || "0");
      let a1 = this.getLeftName(type);
      let aType = a1 ? a1[1] : "";
      if ([18, 38].includes(type)) {
        //导入
        let msg = `覆盖${updateSize}条，导入成功${totalSize -
          errSize}条，导入失败${errSize}条。`;
        if (isDetail) {
          return `您已导入${aType}数据${title}条，` + msg;
        }
        return `导入数据${title}条，` + msg;
      } else {
        //导出
        if (isDetail) {
          return `您已导出${aType}数据${title}条，导出成功${title}条`;
        }
        return `导出数据${title}条，导出成功${title}条`;
      }
    },
    // 转移分配内容
    getTransferData(type, content) {
      let cType = type == 114 ? "分配" : "转移";
      let c1 = this.getLeftName(type);
      let cName = c1[3];
      return cType + cName + "为" + content;
    },
    //  内容-中间
    contentCenterName({ content, title }) {
      if ([1, 2].includes(this.activeMenu)) return content;
      return title;
    },
    // 操作人- 等待审核的无操作人
    realsname({ type, realname, submitUserName }) {
      if (type == "26" || type == "27" || type == "94") {
        return "--";
      } else if (type == "283" || type == "282") {
        return submitUserName;
      } else {
        return realname;
      }
    }
  },
  computed: {
    ...mapState({ leftCount: state => state.crm.leftCount }),
    // 状态
    returnStatus() {
      return ({ type }) => {
        if (this.activeMenu == 0) return "入学成功";
        else if (this.activeMenu == 1) return "退学成功";
        else if (this.activeMenu == 2) return "已逾期";
        else {
          if (
            type == 13 ||
            type == 92 ||
            type == 11 ||
            type == 95 ||
            type == 98 ||
            type == 99
          )
            return "审核通过";
          else if (type == 12 || type == 93 || type == 10) return "审核拒绝";
          else if (type == 27 || type == 94 || type == 26) return "等待审核";
          else if (type == 283 || type == 282) return "已签署";
        }
        return "";
      };
    },
    //数据来源
    dataComefrom() {
      return ({ type }) => {
        let comes = this.getLeftName(type);
        return comes ? comes[0] : "--";
      };
    },
    // 获取列表表头
    commonColumns() {
      let columns = [
        {
          slot: "realname"
        },
        {
          slot: "comefrom",
          label: "数据来源"
        },
        {
          prop: "createTime",
          label: "时间"
        },
        {
          slot: "operate",
          label: "操作"
        }
      ];
      let stuName = {
        slot: "title"
      };
      let content = {
        slot: "content"
      };
      let status = {
        slot: "status"
      };
      let subName = {
        prop: "submitUserName",
        label: "提交人"
      };
      let failReason = {
        slot: "failReason"
      };
      let names = {
        slot: "names"
      };
      let newColumns = [];
      if ([0, 1, 2, 8].includes(this.activeMenu)) {
        //入学通知||退学通知||逾期通知
        newColumns = [stuName, content, status, ...columns];
      } else if ([3, 4, 5].includes(this.activeMenu)) {
        //合同通知||回款通知||退款通知
        newColumns = [subName, content, status, ...columns];
      } else if (this.activeMenu == 6) {
        //导入导出通知
        newColumns = [content, failReason, ...columns];
      } else if (this.activeMenu == 7) {
        //转移分配通知
        newColumns = [names, content, ...columns];
      }
      return [
        {
          slot: "isRead"
        },
        ...newColumns
      ];
    },
    // 透明度
    opacityClass() {
      return row => {
        return row.isRead == 1 ? "opacity_3" : "";
      };
    }
  }
};
</script>
<style scoped lang="scss">
.message-container {
  width: 100%;
  height: 100%;
  background: #ffffff;
  display: flex;
  .msg_r {
    width: calc(100% - 284px);
    padding: 0 16px 16px;
    .top {
      height: 54px;
      border-bottom: 1px solid #ebebeb;
      display: flex;
      justify-content: space-between;
      align-items: center;
      ol {
        display: flex;
        li {
          width: 57px;
          text-align: center;
          margin-right: 30px;
          height: 54px;
          line-height: 60px;
          cursor: pointer;
          font-weight: 400;
          color: #333333;
          font-size: 13px;
        }
        .li_active {
          border-bottom: 2px solid #0066f9;
          color: #0066f9;
        }
      }
    }
    .btm {
      /deep/ .table_padding tr td:first-child div {
        padding-left: 16px !important;
      }
    }
  }
}
// 已读未读状态 start
.has_read,
.un_read {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  display: inline-block;
}
.un_read {
  background: #ff5a00;
}
.has_read {
  background: #e1e1e1;
}
// 已读未读状态 end
.link_to {
  border-bottom: 1px solid #0066f9;
  padding: 0 4px;
  cursor: pointer;
  color: #0066f9;
}
.opacity_3 {
  opacity: 0.8 !important;
}
</style>
